<template>
  <div class="app-container">
    <el-row :gutter="20">
      <splitpanes :horizontal="this.$store.getters.device === 'mobile'"  class="default-theme">
        <!--部门数据-->
        <pane  size="16">
          <el-col >
            <div class="head-container">
              <el-input v-model="typeName" placeholder="设备类型名称" clearable size="small" prefix-icon="el-icon-search" style="margin-bottom: 20px" />
            </div>
            <div class="head-container">
              <el-tree :data="machineryTypeOptions" :props="defaultProps" :expand-on-click-node="false" :filter-node-method="filterNode" ref="tree" node-key="id" default-expand-all highlight-current @node-click="handleNodeClick" />
            </div>
          </el-col>
        </pane>

        <pane size="84">
          <el-col>
               <el-form :inline="true" :model="queryParams" class="demo-form-inline">
                    <el-form-item label="设备编码" prop="machineryCode">
                      <el-input v-model="queryParams.machineryCode" placeholder="请输入设备编码" clearable style="width: 240px" @keyup.enter.native="handleQuery" />
                    </el-form-item>

                    <el-form-item label="设备名称" prop="machineryName">
                      <el-input v-model="queryParams.machineryName" placeholder="请输入设备名称" clearable style="width: 240px" @keyup.enter.native="handleQuery" />
                    </el-form-item>
                    <el-form-item>
                      <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                      <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                    </el-form-item>
               </el-form>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" >新增</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" >修改</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" >删除</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport" >导入</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" >导出</el-button>
            </el-col>
          </el-row>

          <el-table :data="tableData" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column label="设备编码"  prop="machineryCode" align="center" />
            <el-table-column label="设备名称"  prop="machineryName" align="center" />
            <el-table-column label="品牌"  prop="machineryBrand" align="center" />
            <el-table-column label="规格型号"  prop="machinerySpec" align="center" />
            <el-table-column label="所属车间"  prop="workshopName" align="center" />
            <el-table-column label="设备状态"  prop="status" align="center" >
              <template  slot-scope="scope">
                  <dict-tag :options="dict.type.machinery_status" :value="scope.row.status" />
              </template>
            </el-table-column>
            <el-table-column label="创建时间"  prop="createTime" align="center" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                >修改</el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
            <pagination
              v-show="total>0"
              :total="total"
              :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize"
              @pagination="getList"
            />
          </el-col>

        </pane>
      </splitpanes>
    </el-row>

    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <!--添加表单-->
    <el-dialog :title="title" :visible.sync="open" width="700px">
      <el-form :model="form" ref="form"  label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备编码" prop="machineryCode" label-width="120px">
              <el-input v-model="form.machineryCode"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备名称" prop="machineryName" label-width="120px">
              <el-input v-model="form.machineryName"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="品牌" prop="machineryBrand" label-width="120px">
              <el-input v-model="form.machineryBrand"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备分类" prop="machineryTypeName" >
             <el-select v-model="form.machineryTypeName"  ref="machinerySelect"  placeholder="请选择设备分类">
               <el-option style="height:100%; padding: 0;" :value="form.machineryTypeName" :label="form.machineryTypeName">
                 <el-tree
                   :data="machineryTypeOptions"
                   :props="defaultProps"
                   :highlight-current="true"
                   node-key="machineryTypeName"
                   @node-click="handleClick">
                 </el-tree>
               </el-option>
             </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="规格型号" prop="machinerySpec">
              <el-input v-model="form.machinerySpec"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属车间" prop="workshopId">
            <el-select v-model="form.workshopId">
              <el-option
                v-for="item in workshipList"
                :key="item.workshopId"
                :label="item.workshopName"
                :value="item.workshopId"/>
            </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--修改表单-->
    <el-dialog :title="title" :visible.sync="show" width="700px">
      <el-form :model="form" ref="form"  label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备编码" prop="machineryCode" label-width="120px">
              <el-input v-model="form.machineryCode"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备名称" prop="machineryName" label-width="120px">
              <el-input v-model="form.machineryName"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="品牌" prop="machineryBrand" label-width="120px">
              <el-input v-model="form.machineryBrand"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备分类" prop="machineryTypeName" >
              <el-select v-model="form.machineryTypeName"  ref="machinerySelect"  placeholder="请选择设备分类">
                <el-option style="height:100%; padding: 0;" :value="form.machineryTypeName" :label="form.machineryTypeName">
                  <el-tree
                    :data="machineryTypeOptions"
                    :props="defaultProps"
                    :highlight-current="true"
                    node-key="machineryTypeName"
                    @node-click="handleClick">
                  </el-tree>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="规格型号" prop="machinerySpec">
              <el-input v-model="form.machinerySpec"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属车间" prop="workshopId">
              <el-select v-model="form.workshopId">
                <el-option
                  v-for="item in workshipList"
                  :key="item.workshopId"
                  :label="item.workshopName"
                  :value="item.workshopId"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitChangeForm">确 定</el-button>
        <el-button @click="Ccancel">取 消</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import {Pane, Splitpanes} from "splitpanes";
import {deleteType, listTree} from "@/api/dv/type";
import {
  deleteMachinery,
  getMachineryTypeNameById,
  getWorkshop,
  insertMachinery,
  list,
  setMachinery
} from "@/api/dv/machinery";
import 'splitpanes/dist/splitpanes.css'
import Treeselect from "@riophae/vue-treeselect";
import {getToken} from "@/utils/auth";
export default {
  name: "Machinery",
  components: { Treeselect, Splitpanes, Pane },
  dicts:['machinery_status'],
  data() {
    return {
      // 设备台账导入参数
      upload: {
        // 是否显示弹出层（设备台账导入）
        open: false,
        // 弹出层标题（设备台账导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/dv/machinery/importData"
      },
      workshipList:[

      ],
      value:null,
      form:{
        machineryTypeName: null,
        machineryTypeId: null,
        workshopId:null,
        machineryCode:null,
        machineryName:null,
        machineryBrand : null,
        machinerySpec:null,
        machineryId:null,
        remark: null
      },
      open:false,
      show:false,
      title:null,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      tableData:[],
      typeName:undefined,
      machineryTypeOptions:[],
      defaultProps: {
        children: "children",
        label: "machineryTypeName"
      },
      queryParams:{
        pageNum: 1,
        pageSize: 10,
        machineryCode:null,
        machineryName:null,
        machineryTypeId:null,
      },
      // 总条数
      total: 0,
    }
  },
  watch: {

    typeName(newVal) {
      // 通过ref获取树组件实例，调用filter方法传入新的搜索值
      this.$refs.tree?.filter(newVal);
      // ?. 是可选链操作符，避免树组件未渲染时调用filter报错
    }
  },
  methods: {
    // 提交上传文件
    submitFileForm() {
      const file = this.$refs.upload.uploadFiles
      if (!file || file.length === 0 || !file[0].name.toLowerCase().endsWith('.xls') && !file[0].name.toLowerCase().endsWith('.xlsx')) {
        this.$modal.msgError("请选择后缀为 “xls”或“xlsx”的文件。")
        return
      }
      this.$refs.upload.submit()
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true })
      this.getList()
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('dv/machinery/export', {
        ...this.queryParams
      }, `设备台账_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "设备台账导入"
      this.upload.open = true
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('dv/machinery/importTemplate', {
      }, `设备台账模板_${new Date().getTime()}.xlsx`)
    },
    handleDelete(row){
      this.$confirm('确认删除选中的设备吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 执行删除操作
        deleteMachinery(row.machineryId).then(res=>{
          this.$modal.msgSuccess("删除成功")
          this.getTreeList()
          this.getList()
          this.getWorkshopList()
        })
      }).catch(() => {
        // 取消删除
        this.$modal.msgInfo("已取消删除")
      });
    },
    submitChangeForm(){
      if(this.title=='修改'){
        setMachinery(this.form).then(res=>{
          this.$modal.msgSuccess("修改成功")
          this.show=false
          this.getTreeList()
          this.getList()
          this.getWorkshopList()
        })
      }
      this.cancel()
    },
    submitForm(){
      if(this.title=='新增设备'){
        setMachinery(this.form).then(res=>{
          this.$modal.msgSuccess("新增成功")
          this.open=false
          this.getTreeList()
          this.getList()
          this.getWorkshopList()
        })
      }
      this.cancel()
    },
    cancel(){
      this.form.machineryCode=null
      this.form.machineryName=null
      this.form.machineryBrand = null
      this.form.machineryTypeName= null
      this.form.machinerySpec = null
      this.form.workshopId = null
      this.form.machineryId=null
      this.form.remark = null
      this.open = false
    },
    Ccancel(){
      this.form.machineryCode=null
      this.form.machineryName=null
      this.form.machineryBrand = null
      this.form.machineryTypeName= null
      this.form.machinerySpec = null
      this.form.workshopId = null
      this.form.machineryId=null
      this.form.remark = null
      this.open = false
    },
    handleClick(data){
      // 1. 将选中的分类名同步到表单绑定变量（el-select的v-model会自动显示这个值）
      this.form.machineryTypeName = data.machineryTypeName;
      this.form.machineryTypeId = data.machineryTypeId
      console.log(this.form.machineryTypeName)
      console.log(this.form.machineryTypeId)
      // 2. 手动关闭el-select的下拉面板（提升用户体验）
      this.$refs.machinerySelect?.blur();  // 让select失去焦点，关闭下拉
    },
    handleUpdate(row){
      this.form.machineryCode=row.machineryCode
      this.form.machineryName=row.machineryName
      this.form.machineryBrand =row.machineryBrand
      this.form.machineryId=row.machineryId
      console.log("row.machineryId",row.machineryId)
      getMachineryTypeNameById(row.machineryId).then(res=>{
        console.log("res",res.data)
        this.form.machineryTypeName=res.data.machineryTypeName
      })
      this.form.machinerySpec = row.machinerySpec
      this.form.workshopId = row.workshopId
      this.form.remark = row.remark
      this.show = true
      this.title = '修改'
    },
    handleAdd(){
      this.open = true
      this.title = '新增设备'
    },
    resetQuery(){
      this.queryParams = {
        machineryCode:null,
        machineryName:null,
      }
      this.getList()
    },
    handleQuery(){
      this.getList()
    },
    getList(){
      list(this.queryParams).then(res=>{
        this.tableData = res.rows
        this.total = res.total
      })
    },
    getTreeList(){
      listTree().then(res=>{
        console.log("hutool-tree",res.data)
        this.machineryTypeOptions = res.data
      })
    },
    // 筛选节点
    filterNode(value, data) {

      if (!value) return true
      return data.machineryTypeName.indexOf(value) !== -1
    },
    handleNodeClick(data) {
      console.log("点击了节点"+data)
      this.queryParams.machineryTypeId = data.machineryTypeId
      this.handleQuery()
    },
    getWorkshopList(){
      getWorkshop().then(res=>{
        this.workshipList = res.data
        console.log("workshipList",this.workshipList)
      })
    }

  },
  created() {
    this.getTreeList()
    this.getList()
    this.getWorkshopList()
  }
}
</script>

